﻿using System.Text.Json;
using PC_Touch.DataOP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace PC_Touch
{
    public partial class TaskManagement : Form
    {
        public TaskManagement()
        {
            InitializeComponent();
            x = this.Width;
            y = this.Height;
            setTag(this);
            this.Resize += new System.EventHandler(this.IOMonitor_Resize);
        }
        private void IOMonitor_Load(object sender, EventArgs e)
        {
            ReadDBParameter();
        }
        private void ReadDBParameter()
        {
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            var helper = new SQLiteHelper<EventManagement>(connectionString);
            Func<IDataRecord, EventManagement> map = record =>
                        new EventManagement
                        {
                            id = record.GetInt32(0),
                            createDataTime = record.GetString(1),
                            eventName = record.GetString(2),
                            variableAddress = record.GetString(3),
                            variableType = record.GetString(4),
                            eventType = record.GetString(5),
                            eventValue = !record.IsDBNull(6) ? record.GetString(6) : "",
                            remark = record.GetString(7),
                            isEnable = (bool)record.GetValue(8)
                        };
            var value = helper.Query("SELECT * FROM EventManagement", map);
            dataGridView1.DataSource = new BindingList<EventManagement>(value);
            dataGridView1.AllowUserToAddRows = true; // 允许添加新行
            dataGridView1.AllowUserToDeleteRows = true; // 允许删除行
            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; // 设置编辑模式
            dataGridView1.Columns[0].Width = 50;
            dataGridView1.Columns[0].ReadOnly = true;
            dataGridView1.Columns[1].Width = 100;
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.DefaultCellStyle.Font = new Font("Arial", 10, FontStyle.Regular);

            dataGridView1.Columns[1].DefaultCellStyle.Font = new Font("Arial", 8, FontStyle.Bold);


            DataGridViewComboBoxColumn comboBoxColumn0 = new DataGridViewComboBoxColumn();
            comboBoxColumn0.Name = "variableType";
            comboBoxColumn0.HeaderText = "variableType";
            comboBoxColumn0.DataPropertyName = "variableType";
            dataGridView1.Columns.RemoveAt(4); 
            dataGridView1.Columns.Insert(4, comboBoxColumn0);
            List<string> categories0 = new List<string> { "Bool", "Short", "Float", "String" };
            comboBoxColumn0.DataSource = categories0;

            DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();
            comboBoxColumn.Name = "eventType";
            comboBoxColumn.HeaderText = "eventType";
            comboBoxColumn.DataPropertyName = "eventType"; // 数据绑定的列名
            dataGridView1.Columns.RemoveAt(5); // 移除原来的列
            dataGridView1.Columns.Insert(5, comboBoxColumn); // 插入新的下拉列
            List<string> categories = new List<string> {"timerEvent", "changeEvent", "valueUp", "vlaueDown", "valueEqual" };
            comboBoxColumn.DataSource = categories;

            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.Name = "isEnable";
            checkBoxColumn.HeaderText = "isEnable";
            checkBoxColumn.DataPropertyName = "isEnable";
            dataGridView1.Columns.RemoveAt(8); // 移除原来的列
            dataGridView1.Columns.Insert(8, checkBoxColumn); // 插入新的下拉列
            dataGridView1.Columns[8].Width = 80;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            // 可选：设置列标题的字体
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 12, FontStyle.Bold);

            dataCount = dataGridView1.RowCount;
        }
        int dataCount = 0 ;
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            var row = dataGridView1.Rows[e.RowIndex];
            var p = row.DataBoundItem as EventManagement;
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            EventManagementOP op = new EventManagementOP(connectionString);
            if (dataGridView1.Rows.Count > dataCount || dataGridView1.Rows.Count == 0)
            {
                op.AddParameterToDatabase(p);
            }
            else
            {
                op.UpdateParameterInDatabase(p);
            }
            ReadDBParameter();
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this row?", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var p = e.Row.DataBoundItem as EventManagement;
                string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
                EventManagementOP op = new EventManagementOP(connectionString);
                op.DeleteParameterFromDatabase(p);
            }
        }

        #region 控件大小随窗体大小等比例缩放
        private float x = 1;//定义当前窗体的宽度
        private float y = 1;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void IOMonitor_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }

        #endregion
        int i = 0;
        EventListener listener = new EventListener();

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            listener.LoadEvents();
            listener.SubscribeToEvent("M32.0数据上报触发", OnTemperatureChanged);//订阅
        }
        static void OnTemperatureChanged(string eventName, double value)
        {
            GlobalVariable._ConsoleOutputService.Write($"Temperature event triggered: {eventName} changed to {value}");
            Console.WriteLine($"Temperature event triggered: {eventName} changed to {value}");
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            i++;
            listener.SetValue("M32.0数据上报触发", i);
        }
    }

}
